<template>
  <div class="time-range-selector">
    <a-button @click="showTime = true">{{ buttonText }}</a-button>
    <div class="add-time" v-if="showTime">
      <div v-if="props.type === 'time'" class="time-pickers">
        <a-time-picker
          v-model:value="startTime"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="开始时间"
          style="width: 125px"
        />
        <span class="separator">~</span>
        <a-time-picker
          v-model:value="endTime"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="结束时间"
          style="width: 125px"
        />
        <a-button type="primary" size="small" @click="handleSaveTime" style="margin-left: 8px">确定</a-button>
      </div>
      <a-range-picker
        v-else
        v-model:value="timeRange"
        value-format="YYYY-MM-DD"
        format="YYYY-MM-DD"
        separator="~"
        style="width: 258px"
        @change="handleChangeTime"
      />
      <!-- <CheckOutlined @click="handleSaveTime" class="handle-save-time" /> -->
    </div>
    <div class="tag-content">
      <a-tag
        v-for="(item, index) in timeRanges"
        :key="index"
        :closable="!disabled"
        @close="handleCloseTime(index)"
      >
        {{ formatTimeRange(item) }}
      </a-tag>
    </div>
  </div>
</template>

<!-- 时段多选组件 -->
<script setup>

import { CheckOutlined } from "@ant-design/icons-vue"
import { isArray, isObject } from "lodash-es"

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  buttonText: {
    type: String,
    default: "新增时段",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  type: {
    type: String,
    default: "time", // 'time' | 'date'
  },
})

const emit = defineEmits(["update:modelValue", "change"])

const showTime = ref(false)
const timeRange = ref()
const startTime = ref()
const endTime = ref()
const timeRanges = ref(props.modelValue)

// 处理时间选择器的保存
const handleSaveTime = () => {
  if (!startTime.value || !endTime.value) {
    message.warning("请选择开始和结束时间")
    return
  }

  // 使用用户选择的原始顺序
  const newTimeRange = [startTime.value, endTime.value]
  
  // 检查重叠
  const hasOverlap = timeRanges.value.some((period) => {
    const [existStart, existEnd] = isArray(period)
      ? period
      : [period.startTime, period.endTime]
    
    // 检查是否有重叠
    const isOverlapping = checkTimeOverlap(
      startTime.value, 
      endTime.value, 
      existStart, 
      existEnd
    )
    
    return isOverlapping
  })

  if (hasOverlap) {
    message.error("时间段存在重叠，请重新选择")
    return
  }
  const newTimeRanges = [...timeRanges.value, newTimeRange]
  newTimeRanges.sort((a, b) => {
    const timeA = isArray(a) ? a[0] : a.startTime
    const timeB = isArray(b) ? b[0] : b.startTime
    return timeA.localeCompare(timeB)
  })

  timeRanges.value = newTimeRanges
  emit("update:modelValue", newTimeRanges)
  emit("change", newTimeRanges)

  showTime.value = false
  startTime.value = null
  endTime.value = null
}

// 检查时间段是否重叠
const checkTimeOverlap = (startA, endA, startB, endB) => {
  // 将时间转换为分钟数进行比较
  const toMinutes = (timeStr) => {
    const [hours, minutes] = timeStr.split(':').map(Number)
    return hours * 60 + minutes
  }
  
  const startAMin = toMinutes(startA)
  const endAMin = toMinutes(endA)
  const startBMin = toMinutes(startB)
  const endBMin = toMinutes(endB)

  return !(endAMin <= startBMin || startAMin >= endBMin)
}

const handleChangeTime = () => {
  if (!timeRange.value?.length) {
    message.warning("请选择日期区间")
    return
  }

  const [newStart, newEnd] = timeRange.value
  // 检查重叠
  const hasOverlap = timeRanges.value.some((period) => {
    const [existStart, existEnd] = isArray(period)
      ? period
      : [period.startTime, period.endTime]
    return !(newEnd < existStart || newStart > existEnd)
  })

  if (hasOverlap) {
    message.error("日期区间存在重叠，请重新选择")
    return
  }

  const newTimeRanges = [...timeRanges.value, timeRange.value]
  newTimeRanges.sort((a, b) => {
    const timeA = isArray(a) ? a[0] : a.startTime
    const timeB = isArray(b) ? b[0] : b.startTime
    return timeA.localeCompare(timeB)
  })

  timeRanges.value = newTimeRanges
  emit("update:modelValue", newTimeRanges)
  emit("change", newTimeRanges)

  showTime.value = false
  timeRange.value = []
}

const handleCloseTime = (index) => {
  const newTimeRanges = [...timeRanges.value]
  newTimeRanges.splice(index, 1)
  timeRanges.value = newTimeRanges
  emit("update:modelValue", newTimeRanges)
  emit("change", newTimeRanges)
}

const formatTimeRange = (value) => {
  if (isArray(value)) {
    return props.type === "time"
      ? `${value[0]}~${value[1]}`
      : `${value[0]}~${value[1]}`
  }
  if (isObject(value)) {
    return props.type === "time"
      ? `${value.startTime}~${value.endTime}`
      : `${value.startDate}~${value.endDate}`
  }
  return ""
}
</script>

<style lang="less" scoped>
.time-range-selector {
  .add-time {
    margin-top: 10px;
  }
  .handle-save-time {
    margin-left: 10px;
    font-size: 16px;
    cursor: pointer;
  }
  .tag-content {
    width: 390px;
    .ant-tag {
      margin-top: 10px;
      display: inline-block;
    }
  }
  .time-pickers {
    display: flex;
    align-items: center;
    .separator {
      margin: 0 8px;
    }
  }
}
</style>
